package org.lanqiao.ssm.common.mogliefs.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import fm.last.moji.MojiFile;
import fm.last.moji.spring.SpringMojiBean;

@Controller
@RequestMapping(value="/file")
public class FileController {

	@Autowired
	private SpringMojiBean moji = null;

	
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	  public String upload(            
	          HttpServletRequest request, @RequestParam(value = "myFile", required = false) MultipartFile[] files) {
	          try {
	          	for(int i=0;i<files.length;i++){
	          		//1：取得文件名
	          		String fileName = FileUploadUtils.upload(request, files[i]);
	          		//2：根据文件名去获取到对应的FileModel
	          	
	          		
	          		//3：把文件流式上传到 mogilefs里面
	          		//4：获得 远程paths
	          		List<URL> list = this.uploadToMogilefs(123, files[i]);
	          		
	          	
	          		
	          		
	          	}
			} catch (Exception e) {
				e.printStackTrace();
			}
	          return "success";
	  }
	private List<URL> uploadToMogilefs(int uuid , MultipartFile file)throws Exception{
		MojiFile mf = moji.getFile("MyFileKey"+uuid);
		
		OutputStream out = null;
		InputStream in = null;
		try {
			out = mf.getOutputStream();
			in = file.getInputStream();
			
			byte[] bs = new byte[128];
			while( in.read(bs) != -1){
				String s = new String(bs,"utf-8");
				
				out.write(s.getBytes());
				
				bs = new byte[128];
			}
			
			out.flush();
		} finally {
			in.close();
			out.close();
		}
		return mf.getPaths();
	}

}
